//
//  WCIconAndTextFieldCell.m
//  newprojectwindow
//
//  Created by William Towe on 3/24/09.
//  Copyright 2009 Revolution Software. All rights reserved.
//

#import "WCIconAndTextFieldCell.h"
#import "NSImage+FlippedDrawing.h"


#define kWCIconAndTextFieldCellMarginLeft 2.0
#define kWCIconAndTextFieldCellMarginRight 2.0

@implementation WCIconAndTextFieldCell

- (void)dealloc {
	[_icon release];
	[super dealloc];
}

- (NSRect)titleRectForBounds:(NSRect)bounds {
	if (!_icon)
		return [super titleRectForBounds:bounds];
	
	NSRect icon, title;
	NSDivideRect(bounds, &icon, &title, _iconSize.width+kWCIconAndTextFieldCellMarginRight+kWCIconAndTextFieldCellMarginRight, NSMinXEdge);
	return title;
}

- (void)selectWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength {
	[super selectWithFrame:[self titleRectForBounds:aRect] inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
}

- (void)editWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject event:(NSEvent *)theEvent {
	[super editWithFrame:[self titleRectForBounds:aRect] inView:controlView editor:textObj delegate:anObject event:theEvent];
}

- (NSUInteger)hitTestForEvent:(NSEvent *)event inRect:(NSRect)cellFrame ofView:(NSView *)controlView {
	return [super hitTestForEvent:event inRect:[self titleRectForBounds:cellFrame] ofView:controlView];
}

- (id)copyWithZone:(NSZone *)zone {
	WCIconAndTextFieldCell *copy = [super copyWithZone:zone];
	
	copy->_icon = nil;
	copy->_icon = [_icon retain];
	copy->_iconSize = _iconSize;
	
	return copy;
}

@synthesize icon=_icon,iconSize=_iconSize;

- (NSRect)iconRectForBounds:(NSRect)bounds; {
	if (!_icon)
		return NSZeroRect;
	return NSMakeRect(bounds.origin.x+kWCIconAndTextFieldCellMarginLeft, bounds.origin.y+floor((bounds.size.height-_iconSize.height)/2.0), _iconSize.width, _iconSize.height);
}

- (void)drawInteriorWithFrame:(NSRect)frame inView:(NSView *)view {
	if (_icon) {
		NSRect iconRect = [self iconRectForBounds:frame];
		NSImage *icon = [self icon];
		[icon setSize:_iconSize];
		//[icon drawInRect:iconRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
		[icon drawAdjustedInRect:iconRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
	}
	[super drawInteriorWithFrame:[self titleRectForBounds:frame] inView:view];
}
@end
